<template>
    <div class = 'followEdit'>
        <!-- <tmpHeader /> -->
        <h2 style="text-align:center;font-weight:600;margin-bottom:10px;color: #333">表单题目{{title}}</h2>
        <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80" label-position="left">
            <div class="main">
                <p class="title">基本信息</p>
                <div class="box">
                    <FormItem label="题目名称：" prop="question" :label-width="90">
                        <Input v-model.trim="formValidate.question" placeholder="50个汉字以内" maxlength="50" style='width:100%;'></Input>
                    </FormItem>
                    <Row>
                        <Col span="8">
                            <FormItem label="题目类型：" prop="questionType" :label-width="90">
                                <Select v-model="formValidate.questionType" style="width:200px">
                                    <Option v-for="(item, index) in followList" :value="index + 1" :key="index" style='text-align:center;'>{{ item.name }}</Option>
                                </Select>
                            </FormItem>
                        </Col>
                        <Col span="8">
                            <FormItem label="是否使用：" >
                                <iSwitch size="large"  v-model="inused">
                                    <span slot="open">开启</span>
                                    <span slot="close">关闭</span>
                                </iSwitch>
                            </FormItem>
                        </Col>
                    </Row>
                    <!-- 问答题 -->
                    <FormItem label="参考答案信息：" v-if="formValidate.questionType == 3 " :label-width="100">
                        <Input v-model="formValidate.sections"  placeholder="50个汉字以内" maxlength="50" />
                    </FormItem>
                </div>
            </div>
            <div class="main">
                <!-- /宣教科普 -->
                <div v-if="formValidate.questionType == 5 ">
                    <p class="title">详细信息</p>
                    <div class="box">
                        <FormItem style="margin-left:-65px;">
                            <Input v-model="formValidate.sections" type="textarea" placeholder="800个汉字以内" maxlength="800" />
                        </FormItem>
                    </div>
                </div>
                <!-- 单项选择题、选择题加填空题 -->
                <div v-show="formValidate.questionType == 1 || formValidate.questionType == 2 ">
                    <p class="title">选项信息</p>
                    <div class="box">
                        <span style="color:#FF9966;">(注意：输入选项时必须加  “.”  ，例：A. )</span>
                        <Row :gutter="64" style="margin-top:15px">
                            <Col span="21">
                                <Table stripe border :columns="columns1" :data="data1"  ref="myTable" >
                                    <template slot="option" slot-scope="props" >
                                        <Input v-model="props.row.option" placeholder="请输入选项"
                                        ></Input>
                                    </template>
                                    <template slot="solution" slot-scope="props" >
                                        <div style="margin: 10px 0">
                                            <Input v-model="props.row.solution" placeholder="请输入答案信息"
                                        ></Input>
                                            <div style="display: flex;margin-top:5px" v-if="formValidate.questionType == 2 && props.row._index == selection">
                                                <p style="margin-bottom: 10px">参考答案信息：</p>
                                                <Input v-model="answerSelect" placeholder="请输入参考答案信息，100字以内" type="textarea" maxlength="100"
                                                ></Input>
                                            </div>
                                        </div>
                                    </template>
                                    <!-- 参考答案选项 -->
                                    <template slot="answer" slot-scope="props" >
                                        <span v-if="formValidate.questionType == 1 || formValidate.questionType == 2" style="width: 22px;height:22px;border-radius: 11px;display: inline-block;line-height: 20px;margin-top:15px;border: 1px solid #999" :class="{'bg': props.row._index == selection , 'bdc': props.row._index != selection }" @click="changeStatus(props.row)">
                                            <i class = "iconfont icon-save" style="font-size:18px;margin-right:5px;color:#fff;text-align: center;" v-if=" props.row._index == selection"></i>
                                        </span>
                                    </template>
                                </Table>
                            </Col>
                            <Col>
                                <Button type='primary' @click="add">
                                    <i class = "iconfont icon-add" style="font-size:14px;margin-right:5px"></i>添加选项
                                </Button>
                            </Col>
                        </Row>
                    </div>
                </div>
                <!-- 多项选择题 -->
                <div v-show='formValidate.questionType == 4' >
                    <p class="title">选项信息</p>
                    <div class="box">
                        <span style="color:#FF9966;">(注意：输入选项时必须加  “.”  ，例：A. )</span>
                        <Row :gutter="64" style="margin-top:15px">
                            <Col span="21">
                                <Table ref="selection" border stripe  :columns="columns2" :data="data2" @on-selection-change="selectChange" class="table2">
                                    <template slot="option" slot-scope="props" >
                                    <Input v-model="props.row.option" placeholder="请输入选项"
                                    ></Input>
                                    <!-- <span v-else>{{ props.row.option }}</span> -->
                                    </template>
                                    <template slot="solution" slot-scope="props" >
                                        <div style="margin: 10px 0">
                                            <Input v-model="props.row.solution" placeholder="请输入答案信息"
                                        ></Input>
                                            <div style="display: flex;margin-top:5px" v-if="formValidate.questionType == 2 && props.row._index == selection">
                                                <p style="margin-bottom: 10px">参考答案信息：</p>
                                                <Input v-model="answerSelect" placeholder="请输入参考答案信息，100字以内" type="textarea" maxlength="100"
                                                ></Input>
                                            </div>
                                        </div>
                                    </template>
                                    <!-- 参考答案选项 -->
                                    <template slot="answer" slot-scope="props">
                                        <Checkbox
                                            :indeterminate="indeterminate"
                                            :value="checkAll"
                                            @click="handleCheckAll">全选
                                        </Checkbox>
                                        <span>全选</span>
                                        <CheckboxGroup v-model="answers" v-if="formValidate.questionType == 4 ">
                                            <Checkbox label="props.row.option" value='props.row.option' content = '' on-change = checkChange(props.row)></Checkbox>
                                        </CheckboxGroup>
                                    </template>
                                </Table>
                            </Col>
                            <Col>
                                <Button type='primary' @click="add">
                                    <i class = "iconfont icon-add" style="font-size:14px;margin-right:5px"></i>添加选项
                                </Button>
                            </Col>
                        </Row>
                    </div>
                </div>
            </div>
        </Form>
        <div style="width:100%;text-align:center;margin: 10px 0;">
            <Button type="primary" @click="handleSubmit('formValidate')" :disabled='disabledSave' style="width:75px;height:35px;">
                <Icon type="ios-checkmark" style="margin-right: 5px" />保存
            </Button>
            <Button @click="handleReset('formValidate')" style="margin-left: 8px;width:75px;height:35px;">
                <i class = "iconfont icon-butongyi" style="font-size:14px;margin-right:5px"></i>取消
            </Button>
        </div>
    </div>
</template>
<script>
import tmpHeader from "@/pages/organizat/contentmen/tmpHeader";
import api from "@/api/commonApi";
export default {
    components: {
        tmpHeader
    },
    data () {
        return {
            inused: false,
            pageNo: 1,
            pageSize: 10,
            count: 10,
            id: sessionStorage.getItem("hospitalId"),
            formValidate: {
                questionNumber: "",
                question: "",
                sections:"",
                questionType: 1,
                answerSelect:"",
                education:"",
            },
            ruleValidate: {
                questionNumber: [{ required: true, message: '请输入题号', trigger: 'blur', type:'number' }],
                question: [{ required: true, message: '请输入问题', trigger: 'blur' }],
                sections: [{ required: true, message: '请输入选择题答案', trigger: 'blur' }],
                questionType: [{ required: true, message: '请输入题目类型', trigger: 'change', type:'number'}],
                answerSelect: [
                        { required: true, message: '请输入填空题答案', trigger: 'blur' },
                        // { type: 'string', min: 20, message: 'Introduce no less than 20 words', trigger: 'blur' }
                    ]
            },
            followList: [
                { name:'单项选择题',id:1 },
                { name:'选择题加填空题',id:2 },
                { name:'问答题',id:3 },
                { name:'多项选择题',id:4 },
                { name:'宣教科普',id:5 },
            ],
            formId:"",
            status: false,
            data1: [],
            columns1: [
                {
                    key: "option",
                    title: "选项",
                    align: "center",
                    width: 100,
                    render: (h, params) => {
                        this.data1[params.index] = params.row
                        let option = params.row.option;

                        return h(
                            'div',
                            this.$refs.myTable.$scopedSlots.option({
                                row: params.row,
                                idx: params.row._index
                            })
                        )
                    }
                },
                {
                    key: "solution",
                    title: "选项信息",
                    align: "center",
                    render: (h, params) => {
                        this.data1[params.index] = params.row
                            return h(
                                'div',
                                this.$refs.myTable.$scopedSlots.solution({
                                    row: params.row,
                                    idx: params.row._index
                                })
                            )
                    }
                },
                {
                    key: "answer",
                    title: "参考答案选项",
                    align: "center",
                    width: 200,
                    render: (h, params) => {
                        this.data1[params.index] = params.row
                        let answer = params.row.answer;
                        return h(
                            'div',
                            this.$refs.myTable.$scopedSlots.answer({
                                row: params.row,
                                idx: params.row._index
                            }),

                        )
                    }
                },
                {
                    key: "operate",
                    title: "设置",
                    align: "center",
                    width:150,
                    render: (h, params) => {
                        let row = params.row;
                        return [
                            h('Button',{
                                style: {
                                    background: "#fff",
                                    color: " #5362e1",
                                    borderRadius: "15px",
                                    border: "1px solid  #5362e1",
                                    width: "60px"
                                },
                                on: {
                                click: () => {
                                    this.del(params,row)
                                }
                                }
                            },'删除'),
                        ]
                    }
                },
            ],
            currentChoose: [],
            columns2: [
                {
                    key: "option",
                    title: "选项",
                    align: "center",
                    width: 120,
                    render: (h, params) => {
                        this.data2[params.index] = params.row
                        let option = params.row.option;

                        return h(
                            'div',
                            this.$refs.selection.$scopedSlots.option({
                                row: params.row,
                                idx: params.row._index
                            })
                        )
                    }
                },
                {
                    key: "solution",
                    title: "选项信息",
                    align: "center",
                    render: (h, params) => {
                        this.data2[params.index] = params.row
                            return h(
                                'div',
                                this.$refs.selection.$scopedSlots.solution({
                                    row: params.row,
                                    idx: params.row._index
                                })
                            )
                    }
                },
                {
                    key: "answer",
                    title: "参考答案选项",
                    type: 'selection',
                    align: "center",
                    width:200,
                    render: (h, params) => {
                        let flag = false;
                        this.data2[params.index] = params.row
                        return h('div',
                            [
                                h("Checkbox", {
                                    props: {
                                        value: flag,
                                        type: selection,
                                    },
                                    on: {
                                        "on-change": () => {
                                            flag=!flag
                                            if(flag == true){
                                                this.currentChoose.push(params.row);
                                                this.selectChange(this.currentChoose)
                                            }
                                            if(flag == false){
                                                this.currentChoose.forEach(i =>{
                                                    console.log(i)
                                                    this.currentChoose.splice(i._index,1)
                                                })
                                               this.selectChange(this.currentChoose)
                                                console.log(this.currentChoose)
                                            }
                                        }
                                    }
                                })
                            ],
                            this.$refs.selection.$scopedSlots.answer({
                                row: params.row,
                                idx: params.row._index
                            }),

                        )
                    }
                },
                {
                    key: "operate",
                    title: "设置",
                    align: "center",
                    width:150,
                    render: (h, params) => {
                        let row = params.row;
                        return [
                            h('Button',{
                                style: {
                                    background: "#fff",
                                    color: " #5362e1",
                                    borderRadius: "15px",
                                    border: "1px solid  #5362e1",
                                    width: "60px"
                                },
                                on: {
                                click: () => {
                                    this.del(params,row)
                                }
                                }
                            },'删除'),
                        ]
                    }
                },
            ],
            data2: [],
            type: 0,
            subjectid: '',
            title: '新增',
            solution: '',
            answer: '',
            selection: -1,
            answerSelect: '',
            option: '',
            info: '',
            answers: [],
            selectList: [],
            disabledSave: false,
            indeterminate: true,
            checkAll: false,
        }
    },
    created() {
        let breadList = [
        { path: "/index", title: "首页" },
        {
            path: "/index/operation/mechanism/index",
            title: "机构运营"
        },
        {
            path: "/index/operation/followForm/index",
            title: "随访表单"
        }
        ];
        this.$emit("changeBreadList", breadList);
    },
    mounted () {
        if(this.$route.params.id){
            this.subjectid = this.$route.params.id;
            this.title = "编辑"
            this.getsubjectbyid()
        }
    },
    methods: {
         handleCheckAll () {
            if (this.indeterminate) {
                this.checkAll = false;
            } else {
                this.checkAll = !this.checkAll;
            }
            this.indeterminate = false;

            if (this.checkAll) {
                this.currentChoose = this.data2;
            } else {
                this.currentChoose = [];
            }
        },
        //添加选项
        add(){
            this.editIndex = '-1'
            if( this.formValidate.questionType == 1 || this.formValidate.questionType == 2 ){
                this.data1.push({
                    option: '',
                    solution: '',
                    answerSelect: '',
                })
                this.data1[0]._index = 0;
                this.changeStatus(this.data1[0]);
            }
            if(this.formValidate.questionType == 4){
                this.data2.push({
                    option: '',
                    solution: '',
                    answerSelect: '',
                })
            }
            // if(this.selection == val){
            //     this.data1.answer = this.option
            // }
        },
        //删除选项
        del(params,row){
            if( this.formValidate.questionType == 1 || this.formValidate.questionType == 2 ){
                this.data1.forEach((i,index) =>{
                    if(index == row._index){
                        this.data1.splice(row._index, 1)
                        if(this.answerSelect){
                            this.answerSelect = ''
                        }
                    }
                })
            }
            if(this.formValidate.questionType == 4){
                this.data2.forEach((i,index) =>{
                    if(index == row._index){
                        this.data2.splice(row._index, 1)
                        if(this.answerSelect){
                            this.answerSelect = ''
                        }
                    }
                })
            }
        },
        //返回列表页
        back () {
            let params = {}
            this.functionJS.queryNavgationTo(
                this,
                "/index/operation/followForm/index",
                params
            );
        },
        //单选参考答案选项
        changeStatus(val){
            this.selection = val._index
            this.answer = val.option
        },
        //多选参考答案选项
        selectChange(selection){
            let that = this;
            this.selectList = selection;
            this.answer = ''
            this.selectList.forEach(i =>{
                this.answer +=  i.option +"&&"
            })
            console.log(this.answer)
            console.log(this.selectList)
        },
        //获取题目详情
        getsubjectbyid(){
            this.type = 1
            let params = {}
            let arr
            params.id = this.subjectid;
            this.$axios.post(api.questionBankById, params).then(res => {
                if(res.data.success) {
                    let ret = res.data.object;
                    this.inused = Boolean(ret.inused)
                    this.answerSelect = ret.answerSelect
                    this.answer = ret.answer
                    this.formValidate.question = ret.question
                    this.formValidate.questionType = Number(ret.questionType)
                    this.formValidate.answerSelect = ret.answerSelect
                    this.formValidate.sections = ret.sections
                    //拆分展示选项信息
                    arr = ret.sections
                    //去除字符串最后两位
                    // arr = arr.substr(0,arr.length - 2)
                    // console.log(arr)
                    // 字符串转数组
                    let ss = arr.split("&&")
                    // console.log(ss)
                    //数组转换json数组类型
                    var rs = [],a=[],b=[],key=['option','solution'];
                    rs = ss.map(function(item,index){
                        let z = item.split(".")[0]
                        z = z + '.'
                        a.push(z)
                        // a.push(item.split(".")[0])
                        b.push(item.split(".")[1])
                        // console.log(a)
                        var obj ={};               
                        obj[key[0]] = a[index];
                        obj[key[1]] = b[index];
                        return obj;
                    });
                    //单选题和选择加填空回显参考答案选项
                    if(this.formValidate.questionType == 1 || this.formValidate.questionType == 2 ){
                        this.data1 = rs
                        if(this.answer){
                            // this.answer = this.answer.substr(0,this.answer.length - 1)
                            this.data1.forEach((i,index )=>{
                                if(this.answer == i.option){
                                    this.selection = index
                                }
                            })
                        }
                    }

                    //多选题回显参考答案选项
                    if(this.formValidate.questionType == 4){
                        this.data2 = rs
                        if(this.answer){
                            // this.answer = this.answer.substr(0,this.answer.length - 2)
                            console.log(this.answer)
                            let qq = this.answer.split("&&")
                            let selection = []
                            qq.forEach(k =>{
                                this.data2.forEach((i,index )=>{
                                    //获取已选参考答案选项的下标
                                    if(k == i.option){
                                        selection.push(i)
                                        this.selectList = selection
                                    }
                                })
                            })
                            this.selectedTrue()
                        }
                    }
                } else {
                    this.$Message.error('查询失败')
                }
            })
        },
        // 多选题回显勾选
        selectedTrue() {
            setTimeout(() => {
                let tableData = JSON.parse(JSON.stringify(this.data2))
                this.selectList.forEach(el => {
                    let index = tableData.findIndex(i => {
                        return el.option == i.option
                    })
                    if (index != -1) {
                        this.$refs.selection.objData[index]._isChecked = true
                    }
                })
            }, 0)
        },
        //保存
        handleSubmit (name) {
            this.disabledSave = true
            this.$refs[name].validate((valid) => {
                if (valid) {
                    let url = ''
                    let params = {}
                    let sections = ''
                    params.question = this.formValidate.question
                    params.questionType = this.formValidate.questionType
                    params.answerSelect = this.formValidate.answerSelect
                    params.inused = Number(this.inused)
                    params.answer = this.answer;
                    params.answerSelect = this.answerSelect;
                    params.hospitalId = this.id;
                    if(this.formValidate.questionType == 3 || this.formValidate.questionType == 5  ){
                        params.sections = this.formValidate.sections
                    }
                    if(this.formValidate.questionType == 1 || this.formValidate.questionType == 2){
                        let flag = true;
                        if(this.data1.length) {
                            this.data1.forEach(i =>{
                                // let aa = i.option.substr(i.option.length-1,1)
                                // if(aa != '.') {
                                //     flag = false;
                                // }
                                // sections +=  i.option +i.solution +"&&"
                                if(i.option.indexOf('.')>-1){
                                    sections +=  i.option + i.solution +"&&"
                                }else{
                                    sections +=  i.option + '.' +i.solution +"&&"
                                }
                            })
                            params.sections = sections.substr(0,sections.length - 2)
                            // if(flag) {
                            //     params.sections = sections.substr(0,sections.length - 2)
                            // } else {
                            //     this.$Message.error("选项列输入不规范，请按规定操作")
                            //     this.disabledSave = false
                            //     return
                            // }
                        } else {
                            this.disabledSave = false
                            this.$Message.error("请添加选项")
                            return
                        }
                    }
                    if( this.formValidate.questionType == 4 ){
                        if(this.data2.length) {
                            this.data2.forEach(i =>{
                                if(i.option.indexOf('.')>-1){
                                    sections +=  i.option + i.solution +"&&"
                                }else{
                                    sections +=  i.option + '.' +i.solution +"&&"
                                }
                            })
                            params.sections = sections.substr(0,sections.length - 2)
                        } else {
                            this.disabledSave = false
                            this.$Message.error("请添加选项")
                            return
                        }
                    }
                    if(!Boolean(this.subjectid)) {
                        url = api.insertquestion
                    } else {
                        url = api.updatequestion
                        params.id = this.subjectid
                    }
                    this.$axios.post(url, params).then(res => {
                        if(res.data.success) {
                            let ret = res.data.object
                            this.$Message.success("表单题目保存成功")
                            setTimeout(() => {
                                this.disabledSave = false
                            }, 10000);
                            this.handleReset('formValidate');
                        } else {
                            // let message = res.data.object.same || res.data.object.file || '保存失败'
                            let message = '保存失败'
                            this.$Message.error(message)
                            this.disabledSave = false
                        }
                    }).catch(err => {
                        this.disabledSave = false
                    });
                } else {
                    this.$Message.error('请完整填写必填项!');
                    this.disabledSave = false
                }
            })
        },
        //清空S
        handleReset (name) {
            this.$refs[name].resetFields();
            this.formValidate.questionNumber = ''
            this.formValidate.question = ''
            this.formValidate.sections = ''
            this.formValidate.questionType = ''
            this.formValidate.answerSelect = ''
            this.formValidate.id = ''
            this.data1 = []
            let pageNo = this.$route.params.pageNo;
            this.functionJS.paramsNavgationTo(this,
            "questionList",
            {
                // 公用方法
                pageNo
            }
            );
        }
    }
}
</script>
<style lang="less" scoped>
.followEdit{
    width: 100%;
    padding: 10px 0px;
    margin: 0 auto;
    background: #fff;
    .bg{
        background-color: #5362e1;
    }
    .bgc{
        background-color:#fff;
    }
    .main {
        width: 98%;
        display: flex;
        flex-direction: column;
        margin: 10px auto;
        border: 1px solid #f0f0f0;
        box-shadow: 0 4px 3px #ebedf8;
        border-radius: 5px;
        margin-bottom: 20px;
        .box{
            padding: 0 40px 20px 40px;
        }
        .title {
            font-size: 20px;
            padding-left: 15px;
            margin-bottom: 20px;
            color: #333;
            height: 40px;
            line-height: 40px;
            background: #ebedf8;
        }
    }
}
.table2 {
    .ivu-modal-header {
        border-bottom: 1px solid #e8eaec;
        padding: 14px 16px;
        line-height: 1;
    }
    th .ivu-table-cell-with-selection{
        position: relative;
    }
    th .ivu-table-cell-with-selection::after{
        content: '';
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        background: #f8f8f9;
        z-index: 99;
    }
}
</style>
